﻿using System;
using System.Text;

namespace YArchitech.LIB
{
	public class StringTools
	{
		public static string DoubleToString(double dValue, int precision = 3)
		{
			char c = '.';
			char[] trimChars = new char[]
			{
				'0'
			};
			if (Math.Abs(dValue) < 1E-05)
			{
				return "0";
			}
			string text = dValue.ToString();
			text = dValue.ToString("G0");
			if (text.IndexOf(c) > 0)
			{
				string format = string.Format("f{0}", precision);
				text = dValue.ToString(format).TrimEnd(trimChars);
				text = text.TrimEnd(new char[]
				{
					c
				});
			}
			return text;
		}

		public static string RemoveUnit(string str)
		{
			bool flag = true;
			string text = "";
			for (int i = 0; i < str.Length; i++)
			{
				if (str[i] == '.' && flag)
				{
					flag = false;
				}
				else if (!char.IsDigit(str[i]))
				{
					if (i == 1 && !flag)
					{
						text = "";
						break;
					}
					text = str.Substring(0, i);
					break;
				}
			}
			if (text.Length < 1 || text == null)
			{
				return str;
			}
			return text;
		}

		public static string RemoveZero(string str)
		{
			string result = str;
			try
			{
				result = Convert.ToDouble(str).ToString();
			}
			catch (Exception)
			{
			}
			return result;
		}

		public static string CutOffEfficacious(string str, int i)
		{
			if (i < 0)
			{
				return str;
			}
			string result = str;
			try
			{
				result = Math.Round(double.Parse(str), i).ToString();
			}
			catch (Exception)
			{
			}
			return result;
		}

		public static bool IsAlphabet(char key)
		{
			bool result = true;
			if (char.IsDigit(key))
			{
				result = false;
			}
			else if ('+' == key || '-' == key || '.' == key || '\b' == key || '\r' == key)
			{
				result = false;
			}
			return result;
		}

		public static bool IsNumber(char key)
		{
			bool result = false;
			if (char.IsDigit(key))
			{
				result = true;
			}
			else if ('.' == key || '\b' == key)
			{
				result = true;
			}
			return result;
		}

		public static string RemoveSpace(string str)
		{
			string text = "";
			for (int i = 0; i < str.Length; i++)
			{
				if (!char.IsWhiteSpace(str[i]))
				{
					text += str[i].ToString();
				}
			}
			return text;
		}

		public static int GetStringByteLength(string str)
		{
			return Encoding.Default.GetByteCount(str);
		}
	}
}
